package com.abocode.smarten.rpc.server.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * Description:
 * @author: guanxianfei
 * @date: 2019/7/23
 */
@Slf4j
public class NettyServer implements InitializingBean, DisposableBean {
    private int port = 8283;
    private EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    private EventLoopGroup workerGroup = new NioEventLoopGroup();
    private  ServerHandler serverHandler;
    public NettyServer(ServerHandler serverHandler,int port) {
        this.serverHandler = serverHandler;
        this.port = port;
    }

    public void afterPropertiesSet() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .option(ChannelOption.SO_REUSEADDR, true)
                .childHandler(new ServerInitializer(serverHandler));

        b.bind("0.0.0.0", port).sync().channel();
        log.info("Smarten Netty Server starting, post={}", port);
    }

    public void destroy() {
        if(bossGroup != null)
            bossGroup.shutdownGracefully();

        if(workerGroup != null)
            workerGroup.shutdownGracefully();

    }


}
